package com.hr.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hr.entity.Users;
import com.hr.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;

/**
 * 基于dao认证的 实现类
 * 必须实现 ：UserDetailsService 接口
 */
public class UserDetailServiceImpl implements UserDetailsService {
    //操作 users表的mapper
    @Autowired
    private UsersMapper usersMapper;


    /**
     * spring security在接收到前端的登录请求（'/login'）,
     * 会调用此方法来认证身份
     * @param username 前端传递过来的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询条件
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>();
        wrapper.eq("u_name",username);

        //查询单个用户
        Users user = usersMapper.selectOne(wrapper);
        if(user == null){
            throw new UsernameNotFoundException("*** 用户名错误");
        }
        //返回用户对象,注意：权限集合不能为null，否则会报错
        user.setAuthorities(new ArrayList<GrantedAuthority>());
        return user;

    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String s = encoder.encode("123456");
        System.out.println(s);
//        $2a$10$9kts0wq6D3Hs5pIHXGI8g.GFx/7WrDh/MxMPcGCcrD/n/gkERunyG

//        $2a$10$uVqzRgvrpETgsDccvdI8t.maOhSPHghXhj19s7GgpkcK3iZL5RWN2

//        boolean b = encoder.matches("123456","$2a$10$uVqzRgvrpETgsDccvdI8t.maOhSPHghXhj19s7GgpkcK3iZL5RWN2");
//        System.out.println(b);
    }
}
